package com.wl.shop.web;

import java.util.Date;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.google.common.collect.Maps;
import com.wl.shop.entity.Article;
import com.wl.shop.entity.Category;
import com.wl.shop.entity.MyTemplate;
import com.wl.shop.model.RestResponse;
import com.wl.shop.template.TemplateUtil;
import com.wl.shop.utils.UserUtils;

import freemarker.template.Template;

@Controller
@RequestMapping("${adminPath}/category")
public class CategoryController extends BaseController {
	
	@GetMapping({"list",""})
	public String list(@RequestParam(value = "id",required = false)String id,Model model){
		logger.info("跳转菜单列表---");
		if("1".equals(id)){
			return "cms/category/list";
		}
		model.addAttribute("tree", UserUtils.getCategoryTreeString());
		if(StringUtils.isNotBlank(id)){
			Map<String,Object> map = Maps.newHashMap();
			map.put("id", id);
			Category c = categoryService.selectCategoryByParam(map);
			model.addAttribute("category", c);
		}
		return "cms/category/list";
	}
	
	@GetMapping("add")
	public String add(@RequestParam(value = "parentId",required = false)String parentId,Model model){
		if(StringUtils.isNotBlank(parentId)){
			Category parentCategory= categoryService.selectById(parentId);
			model.addAttribute("parentCategory", parentCategory);
		}
		List<MyTemplate> listTemplates = templateService.selectList(new EntityWrapper<MyTemplate>().eq("is_del", false).eq("type", 1));
		List<MyTemplate> contentTemplates = templateService.selectList(new EntityWrapper<MyTemplate>().eq("is_del", false).eq("type", 2));
		model.addAttribute("listTemplates", listTemplates);
		model.addAttribute("contentTemplates", contentTemplates);
		return "cms/category/add";
	}
	
	@PostMapping("add")
	@ResponseBody
	public RestResponse add(@RequestBody Category category){
//		if(StringUtils.isBlank(category.getParentId())){
//			return RestResponse.failure("父栏目不能为空");
//		}
		if(StringUtils.isBlank(category.getName())){
			return RestResponse.failure("栏目名称不能为空");
		}
		if(StringUtils.isBlank(category.getModel())){
			return RestResponse.failure("栏目模型不能为空");
		}else{
			if(!"1".equals(category.getModel()) && !"2".equals(category.getModel()) && !"3".equals(category.getModel())){
				return RestResponse.failure("栏目模型数据出错"); 
			}
		}
		if(StringUtils.isBlank(category.getListTemplate())){
			return RestResponse.failure("栏目列表页模板不能为空");
		}
		if(StringUtils.isBlank(category.getContentTemplate())){
			return RestResponse.failure("栏目内容页模板不能为空");
		}
		if("3".equals(category.getModel()) && StringUtils.isBlank(category.getListUrl())){
			return RestResponse.failure("栏目模型为外链则地址不能为空");
		}
		if(StringUtils.isNotBlank(category.getEnName())){
			int count = categoryService.selectCount(new EntityWrapper<Category>().eq("en_name", category.getEnName()));
			if(count >0){
				return RestResponse.failure("系统中存在英文名称重复的栏目");
			}
		}
		if(StringUtils.isNotBlank(category.getParentId())){
			Category parentCategory = categoryService.selectById(category.getParentId());
			String parentIds = parentCategory.getParentIds()+category.getParentId()+",";
			category.setParentIds(parentIds);
			String path = parentCategory.getPath()+"/"+category.getEnName();
			category.setPath(path);
		}else{
			category.setParentId("1");
			category.setParentIds("1,");
			category.setPath("/"+category.getEnName());
		}
		category.setSort(categoryService.getMaxSort(category.getParentId())+10);
		categoryService.saveOrUpdate(category);
		return RestResponse.success();
	}
	
	@GetMapping("edit")
	public String edit(String id,Model model){
		Category category = categoryService.selectById(id);
		List<MyTemplate> listTemplates = templateService.selectList(new EntityWrapper<MyTemplate>().eq("is_del", false).eq("type", 1));
		List<MyTemplate> contentTemplates = templateService.selectList(new EntityWrapper<MyTemplate>().eq("is_del", false).eq("type", 2));
		model.addAttribute("category", category);
		model.addAttribute("listTemplates", listTemplates);
		model.addAttribute("contentTemplates", contentTemplates);
		model.addAttribute("tree", UserUtils.getCategoryTreeString());
		return "cms/category/edit";
	}
	
	@PostMapping("edit")
	@ResponseBody
	public RestResponse edit(@RequestBody Category category){
		if(StringUtils.isBlank(category.getId())){
			return RestResponse.failure("栏目ID不能为空");
		}
		if(StringUtils.isBlank(category.getParentId())){
			return RestResponse.failure("父栏目不能为空");
		}
		if(StringUtils.isBlank(category.getName())){
			return RestResponse.failure("栏目名称不能为空");
		}
		if(StringUtils.isBlank(category.getModel())){
			return RestResponse.failure("栏目模型不能为空");
		}else{
			if(!"1".equals(category.getModel()) && !"2".equals(category.getModel()) && !"3".equals(category.getModel())){
				return RestResponse.failure("栏目模型数据出错"); 
			}
		}
		if(StringUtils.isBlank(category.getListTemplate())){
			return RestResponse.failure("栏目列表页模板不能为空");
		}
		if(StringUtils.isBlank(category.getContentTemplate())){
			return RestResponse.failure("栏目内容页模板不能为空");
		}
		if("3".equals(category.getModel()) && StringUtils.isBlank(category.getListUrl())){
			return RestResponse.failure("栏目模型为外链则地址不能为空");
		}
		Category old = categoryService.selectById(category.getId());
		if(!old.getEnName().equals(category.getEnName())){
			if(StringUtils.isNotBlank(category.getEnName())){
				int count = categoryService.selectCount(new EntityWrapper<Category>().eq("en_name", category.getEnName()));
				if(count >0){
					return RestResponse.failure("系统中存在英文名称重复的栏目");
				}
			}
		}
		if(!old.getParentId().equals(category.getParentId())){
			if(!"1".equals(category.getParentId())){
				Category parentCategory = categoryService.selectById(category.getParentId());
				String parentIds = parentCategory.getParentIds()+category.getParentId()+",";
				category.setParentIds(parentIds);
				String path = parentCategory.getPath()+"/"+category.getEnName();
				category.setPath(path);
			}else{
				category.setParentIds("1,");
				category.setPath("/"+category.getEnName());
			}
			category.setSort(categoryService.getMaxSort(category.getParentId())+10);
		}
		categoryService.saveOrUpdate(category);
		return RestResponse.success();
	}
	
	@PostMapping("delete")
	@ResponseBody
	public RestResponse delete(@RequestParam(value = "cid",required = false)String cid){
		if(StringUtils.isBlank(cid)){
			return RestResponse.failure("栏目ID不能为空");
		}
		Category category  = categoryService.selectById(cid);
		if(category == null){
			return RestResponse.failure("ID数据错误");
		}
		EntityWrapper<Article> wrapper = new EntityWrapper<Article>();
		wrapper.eq("is_del", false).eq("category_id", cid);
		List<Article> lists =articleService.selectList(wrapper);
		if(lists != null && lists.size()>0){
			return RestResponse.failure("该栏目里有文章,不能删除");
		}
		categoryService.delete(cid);
		return RestResponse.success();
	}
	
	@GetMapping("changeTemplate")
	public String changeTemplate(String id,int type,Model model){
		Category category = categoryService.selectById(id);
		model.addAttribute("category", category);
		model.addAttribute("categoryId", id);
		model.addAttribute("type", type);
		return "cms/template/select";
	}
	
	@PostMapping("changeTemplate")
	@ResponseBody
	public RestResponse changeTemplate(@RequestBody Category category){
		if(StringUtils.isBlank(category.getId())){
			return RestResponse.failure("ID不能为空");
		}
		categoryService.saveOrUpdate(category);
		return RestResponse.success();
	}	
	
	@PostMapping("toStaticHtml")
	@ResponseBody
	public RestResponse toStaticHtml(@RequestParam(value = "cid",required = false)String cid){
		if(StringUtils.isBlank(cid)){
			return RestResponse.failure("栏目ID不能为空");
		}
		Category category = categoryService.selectById(cid);
		if(StringUtils.isBlank(category.getListTemplate())){
			return RestResponse.failure("栏目没有选择模板");
		}
		if(StringUtils.isBlank(category.getPath())){
			return RestResponse.failure("栏目没有对应生成路径");
		}
		//生成列表页数据
		MyTemplate myTemplate = templateService.selectById(category.getListTemplate());
		TemplateUtil.createHtml(myTemplate, getListMapData(category), TemplateUtil.getHtmlPath(category.getPath()));
		//生成内容页数据
		if(StringUtils.isNotBlank(category.getContentTemplate())){
			MyTemplate contentTemplate = templateService.selectById(category.getContentTemplate());
			if(contentTemplate != null){
				Template template = TemplateUtil.getTemplate(contentTemplate);
				if(template != null){
					EntityWrapper<Article> wrapper = new EntityWrapper<Article>();
					wrapper.eq("is_del", false).eq("category_id", cid);
					List<Article> articles = articleService.selectList(wrapper);
					for (Article article : articles) {
						TemplateUtil.createHtml(template, getContentMapData(category,article), TemplateUtil.getContentHtmlPath(article, category.getPath()));
					}
				}
			}
		}
		category.setPublishDate(new Date());
		categoryService.saveOrUpdate(category);
		return RestResponse.success();
	}
	
	/**
	 * 为生成列表页页面准备数据
	 * @param category
	 * @return
	 */
	private Map<String,Object> getListMapData(Category category){
		Map<String,Object> map = Maps.newHashMap();
		return map;
	}
	
	private Map<String,Object> getContentMapData(Category category,Article article){
		Map<String,Object> map = Maps.newHashMap();
		return map;
	}
}
